package com.situ.web.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.web.util.JDBCUtil;

@WebServlet("/studentInsert")
public class StudentInsertServlet extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 后台不关心前台到底是以get还是post传递过来的，
		// 处理方式是一样的
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("StudentInsertServlet.doPost()");
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 解决post乱码问题
		req.setCharacterEncoding("utf-8");
		
		String name = req.getParameter("name");
		String age = req.getParameter("age");
		String gender = req.getParameter("gender");
		
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "INSERT INTO student(`name`,age,gender) VALUES(?,?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name);
			preparedStatement.setInt(2, Integer.parseInt(age));
			preparedStatement.setString(3, gender);
			System.out.println(preparedStatement);
			int count = preparedStatement.executeUpdate();
			if (count == 1) {
				System.out.println("插入成功");
			} else {
				System.out.println("插入失败");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, preparedStatement, null);
		}
		
		// 重定向到/JavaWeb1907/student
		//resp.sendRedirect(req.getContextPath() + "/student");
		resp.sendRedirect("/JavaWeb1907/student");
		
		// req.getRequestDispatcher("/student").forward(req, resp);
	}
}
